import yt_dlp
import json

def get_download_link(url):
    download_link = None
    video_urls_dict = {
        "720": "",
        "480": "",
        "1080": "",
        "360": "",
        "1440": "",
        "2160": "",
        "other": "",
    }
    audio_urls_dict = {
        "ultralow": "",
        "low": "",
        "medium": "",
    }
    youtube_dl_dict = {
        "videoUrl": "",
        "audioUrl": "",
    }
    ydl_opts = {}
    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(url, download=False)
            for format_data in info_dict.get("formats", []):
#                 print(format_data)
#                 print("\n")
                if (
                    format_data.get("format_note") is not None
                    and format_data.get("url") is not None
                ):
                    note = format_data["format_note"]
                    url = format_data["url"]
                else:
                    continue

                # 获取视频url
                if note.find("720") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["720"] = url
                elif note.find("480") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["480"] = url
                elif note.find("1080") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["1080"] = url
                elif note.find("360") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["360"] = url
                elif note.find("1440") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["1440"] = url
                elif note.find("2160") != -1 and url.find(".m3u8") == -1:
                    video_urls_dict["2160"] = url
                elif (note.find("240") or note.find("144")) and url.find(".m3u8") == -1:
                    video_urls_dict["other"] = url

                # 获取音频url
                if note.find("ultralow") != -1:
                    audio_urls_dict["ultralow"] = url
                elif note.find("low") != -1:
                    audio_urls_dict["low"] = url
                elif note.find("medium") != -1:
                    audio_urls_dict["medium"] = url

            # print(video_urls_dict)

            # 下载优先级：720---480---1080---360---1440---2160---other
            for video_url in video_urls_dict.values():
                if len(video_url) > 0:
                    youtube_dl_dict["videoUrl"] = video_url
                    break

            # 下载优先级：ultralow---low---medium
            for audio_url in audio_urls_dict.values():
                if len(audio_url) > 0:
                    youtube_dl_dict["audioUrl"] = audio_url
                    break

            download_link = json.dumps(youtube_dl_dict)

    except Exception as e:
        download_link = None

    return download_link
